package design.donkey.auto.ddl.analysis;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import design.donkey.auto.ddl.exception.AutoDdlException;
import design.donkey.auto.ddl.util.AutoDdlCommonUtils;
import lombok.Data;

/**
 * 字段模型
 *
 * @author zhangjiakung
 * @since 0.0.1
 */
@Data
public class ModelField {

    /**
     * 
     */
    private int analysisColumnLocation;

    /**
     * 字段名称
     */
    private String name;

    /**
     * 字段
     */
    private Field field;

    /**
     * getter
     */
    private Method getter;

    /**
     * setter
     */
    private Method setter;

    /**
     * 获取字段注解 <br/>
     *
     * 注解优先级从高到低为 {@code filed > getter > setter }
     *
     * @param annotationType 注解类型
     * @return 存在则返回对应注解，不存在则返回 null
     * @param <T> 注解返回类型
     */
    public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
        // 获取 field 中的注解
        T annotation = AutoDdlCommonUtils.getAnnotation(field, annotationType);
        if (annotation != null) {
            return annotation;
        }
        // 获取 getter 中的注解
        annotation = AutoDdlCommonUtils.getAnnotation(getter, annotationType);
        if (annotation != null) {
            return annotation;
        }
        // 获取 setter 中的注解
        annotation = AutoDdlCommonUtils.getAnnotation(setter, annotationType);
        return annotation;
    }

    /**
     * 获取字段类型
     *
     * @return 字段类型
     */
    public Class<?> getFiledType() {
        if (field != null) {
            return field.getType();
        }
        if (getter != null) {
            return getter.getReturnType();
        }
        if (setter != null) {
            return setter.getParameterTypes()[0];
        }
        throw new AutoDdlException("illegal model field");
    }

}
